package com.apes.fico.engine.service;

import com.apes.fico.engine.AccountingEngineImpl;
import com.apes.fico.engine.model.BusinessDocument;
import com.apes.fico.engine.model.TempVoucher;
import com.apes.fico.engine.repository.BusinessDocumentRepository;
import com.apes.fico.engine.repository.TempVoucherRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service("businessDocumentService")
public class BusinessDocumentService extends DomainService {
    @Autowired
    BusinessDocumentRepository businessDocumentRepository;
    @Autowired
    AccountingEngineImpl accountingEngine;
    @Autowired
    TempVoucherRepository tempVoucherRepository;
    /***
     * 生成原始会计凭证
     * @param request
     * @return
     */
    public BusinessDocument translate(SimpleRequest request){

        BusinessDocument businessDocument = request.getO(BusinessDocument.class);
        try{
            TempVoucher tempVoucher = accountingEngine.createVoucher(businessDocument);
            businessDocument.setTempVoucher(MapUtil.mapped(tempVoucher));
            businessDocument.setPostDate(tempVoucher.getPostDate());
            businessDocument.setMessage("");
        } catch (RuntimeException e){
            // 每次调用报错信息可能不一致
            businessDocument.setMessage(e.getMessage());
            businessDocument.setState("unusual");   // 设置状态为异常
            businessDocument = businessDocumentRepository.saveAndFlush(businessDocument);
            businessDocument.setErr(true);
        }
        return businessDocument;
    }

    /***
     * 保存财务凭证
     * @param request
     * @return
     */
    public BusinessDocument approve(SimpleRequest request){
        BusinessDocument businessDocument = request.getO(BusinessDocument.class);
        Map map = businessDocument.getTempVoucher();

        // map 转 JavaBean
        TempVoucher tempVoucher = MapUtil.getO(map, TempVoucher.class);

        tempVoucher = accountingEngine.save(tempVoucher);

        businessDocument.setState("generated");
        businessDocument.setPostDate(tempVoucher.getPostDate());
        businessDocument.setMessage("凭证生成成功！" + tempVoucher.getId());
        businessDocument =  businessDocumentRepository.saveAndFlush(businessDocument);

        businessDocument.setTempVoucher(MapUtil.mapped(tempVoucher));
        return businessDocument;
    }


}
